package com.geek.water.utils;

import com.geek.water.constant.BillingConstants;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 账单编号生成器
 * 生成格式：WT + 年月日 + 三位序列号
 * 例如：WT20250806005
 */
public class BillCodeGenerator {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final AtomicInteger SEQUENCE = new AtomicInteger(1);
    private static volatile String lastDate = "";

    /**
     * 生成账单编号
     * 格式：WT + 年月日 + 三位序列号
     * 例如：WT20250806005
     */
    public static String generateBillCode() {
        try {
            LocalDate today = LocalDate.now();
            String dateStr = today.format(DATE_FORMATTER);

            // 如果日期变化，重置序列号
            if (!dateStr.equals(lastDate)) {
                SEQUENCE.set(1);
                lastDate = dateStr;
            }

            int sequence = SEQUENCE.getAndIncrement();

            // 如果序列号超过最大值，重置为1
            if (sequence > BillingConstants.MAX_SEQUENCE) {
                SEQUENCE.set(1);
                sequence = 1;
            }

            return String.format("%s%s%03d", BillingConstants.BILL_CODE_PREFIX, dateStr, sequence);
        } catch (Exception e) {
            throw new RuntimeException("生成账单编号失败: " + e.getMessage(), e);
        }
    }

    /**
     * 根据指定日期生成账单编号
     * 格式：WT + 年月日 + 三位序列号
     */
    public static String generateBillCode(LocalDate date) {
        try {
            if (date == null) {
                throw new RuntimeException("日期参数不能为空");
            }

            String dateStr = date.format(DATE_FORMATTER);

            // 如果日期变化，重置序列号
            if (!dateStr.equals(lastDate)) {
                SEQUENCE.set(1);
                lastDate = dateStr;
            }

            int sequence = SEQUENCE.getAndIncrement();

            // 如果序列号超过最大值，重置为1
            if (sequence > BillingConstants.MAX_SEQUENCE) {
                SEQUENCE.set(1);
                sequence = 1;
            }

            return String.format("%s%s%03d", BillingConstants.BILL_CODE_PREFIX, dateStr, sequence);
        } catch (Exception e) {
            throw new RuntimeException("生成账单编号失败: " + e.getMessage(), e);
        }
    }

    /**
     * 重置序列号计数器
     */
    public static void resetSequence() {
        SEQUENCE.set(1);
        lastDate = "";
    }
}